from flask import Flask, request, jsonify
from flask_cors import CORS  # 导入Flask-CORS库
import random
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.14.0
from dashscope import Generation
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
app = Flask(__name__)
CORS(app) 

def call_with_stream():
    messages = [
        {'role':'system','content':'you are a helpful assistant'},
        {'role': 'user','content': '你是谁？'}
        ]
    responses = Generation.call(
        model="qwen-turbo",
        api_key='sk-3c0aee84e5b74dfcb5e36b4b1679a97e',
        messages=messages,
        # 设置输出为'message'格式
        result_format='message',
        # 设置输出方式为流式输出
        stream=True,
        # 增量式流式输出
        incremental_output=True
        )
    full_content = ""
    for response in responses:
        if response.status_code == HTTPStatus.OK:
            print(response)
            full_content += response.output.choices[0].message.content
        else:
            print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
                response.request_id, response.status_code,
                response.code, response.message
            ))
    print(f"Full content:{full_content}")

if __name__ == '__main__':
    call_with_stream()